/*
 * @lc app=leetcode.cn id=783 lang=typescript
 *
 * [783] 二叉搜索树节点最小距离
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function minDiffInBST(root: TreeNode | null): number {
    if (!root) throw new Error("错误");

    // 中序ji
    const tra = (node: TreeNode | null): number[] => {
        if (!node) return [];
        return [...tra(node.left), node.val, ...tra(node.right)];
    };

    // 经过排序的数字，找两个直接的最小值
    let min = Infinity;
    const list = tra(root);
    for (let index = 1; index < list.length; index++) {
        const prev = list[index - 1];
        const element = list[index];
        min = Math.min(min, element - prev);
    }
    return min;
}
// @lc code=end
